package com.vd.tbsms.ui;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.swing.event.EventListenerList;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

public class TbsmsTableModel implements TableModel{
	private List<?> dataList ;
	public List<?> getDataList() {
		return dataList;
	}

	public void setDataList(List<?> dataList) {
		this.dataList = dataList;
		fireEvent(new TableModelEvent(this));
	}

	public List<String> getHeaderList() {
		return headerList;
	}

	public void setHeaderList(List<String> headerList) {
		headerList.add(0, "发送状态");
		this.headerList = headerList;
		fireEvent(new TableModelEvent(this,TableModelEvent.HEADER_ROW));
	}

	private List<String> headerList= Arrays.asList("发送状态","邮箱","姓名");
	/** List of listeners */
	protected EventListenerList listenerList = new EventListenerList();
	@Override
	public void addTableModelListener(TableModelListener l) {
		listenerList.add(TableModelListener.class,l);
	}

	@Override
	public Class<?> getColumnClass(int columnIndex) {
		return Object.class;
	}

	@Override
	public int getColumnCount() {
		if(headerList == null)
			return 0;
		else
		return this.headerList.size();
	}

	@Override
	public String getColumnName(int columnIndex) {
		return this.headerList.get(columnIndex);
	}

	@Override
	public int getRowCount() {
		if(this.dataList == null)
			return 0;
		else
			return this.dataList.size();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		Map map=(Map) this.dataList.get(rowIndex);
		return map.get(headerList.get(columnIndex));
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return false;
	}

	@Override
	public void removeTableModelListener(TableModelListener l) {
		listenerList.remove(TableModelListener.class, l);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setValueAt(Object value, int rowIndex, int columnIndex) {
		Map map=(Map) this.dataList.get(rowIndex);
		map.put(headerList.get(columnIndex), value);
		fireEvent(new TableModelEvent(this,rowIndex));
	}
	private void fireEvent(TableModelEvent event){
		// Guaranteed to return a non-null array
		Object[] listeners = listenerList.getListenerList();
		// Process the listeners last to first, notifying
		// those that are interested in this event
		for (int i = listeners.length-2; i>=0; i-=2) {
		    if (listeners[i]==TableModelListener.class) {
			((TableModelListener)listeners[i+1]).tableChanged(event);
		    }
		}
		
	}

}
